<?php

namespace App\Kuafu\WaiMai\Command;

use App\Kuafu\Config\Model\ConfigModel;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\WaiMai\Channel\BaseWaiMai;
use App\Kuafu\WaiMai\Channel\ElmWaiMai;
use App\Kuafu\WaiMai\Enum\WaiMaiCodeEnum;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Model\WaiMaiCallbackLogModel;
use App\Kuafu\WaiMai\Model\WaiMaiOrderIdShopIdMappingModel;
use App\Kuafu\WaiMai\Service\BaseWaiMaiOrderService;
use App\Library\FeiShu\SendFs;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class ElmPullErrCallback extends Command
{
    protected $signature = 'waimai:elm-pull-err-callback {auto?}';

    protected $description = '饿了么拉取失败回调';

    public function handle()
    {
        $auto = $this->argument('auto') ?? 0;

        if (isTest()) {
            $shopId = 1; // 需要走沙箱的标记

            if ($auto) {
                dump('qa环境cron不执行');
                return;
            }

        } else {
            $shopId = 0;
        }

        $lists = BaseWaiMai::getIns(WaiMaiDBEnum::SOURCE_TYPE_ELM, $shopId)
                           ->getPushFailMsg()['oriData']['msgList'] ?? [];

//        dump($lists);

        if ($lists) {
            Log::channel('waiMai')->info("ElmPullErrCallback lists full", $lists);
        } else {
            Log::channel('waiMai')->info("ElmPullErrCallback lists empty");
        }

        foreach ($lists as $val) {
            $messageType = $val['messageType'] ?? '';
            $orderId     = $val['orderId'] ?? '';
            $messageId   = $val['messageId'] ?? '';
            $message     = $val['message'] ?? '';
            $gmtCreate   = $val['gmtCreate'] ?? '';

            if (!$orderId) {
                continue;
            }

            try {
                // 处理数据
                $requestData = json_decode($message, true);
                $requestData['type'] = $messageType;
                $run = BaseWaiMaiOrderService::getIns(CodeEnum::SOURCE_TYPE_ELM)
                                      ->setRequestData($requestData)
                                      ->run(1);

                Log::channel('waiMai')->info("ElmPullErrCallback: {$orderId} {$messageType} {$run}");

                // 处理完成 - 上报
                $res = BaseWaiMai::getIns(WaiMaiDBEnum::SOURCE_TYPE_ELM, $shopId)
                                 ->confirmPullMsg($messageId);
                dump($res);

            } catch (\Exception $e) {
                Log::channel('waiMai')->info($e);
            }
        }
    }
}
